package com.sun.future;

import java.util.concurrent.*;

public class SupplyAsyncExample {
    // 创建自定义线程池（实际项目中应根据需求配置合适的线程池）
    private static final ExecutorService customExecutor = Executors.newFixedThreadPool(3);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程开始: " + Thread.currentThread().getName());

        // 1. 使用默认线程池（ForkJoinPool.commonPool()）
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("supplyAsync任务执行线程: " + Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1); // 模拟耗时操作
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            return "Hello from supplyAsync with default executor";
        });

        // 2. 使用自定义线程池
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("supplyAsync任务执行线程: " + Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1); // 模拟耗时操作
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            return "Hello from supplyAsync with custom executor";
        }, customExecutor);

        // 获取结果（会阻塞主线程直到任务完成）
//        System.out.println("future1结果: " + future1.get());
        System.out.println("future1结果: " + future1.join());
//        System.out.println("future2结果: " + future2.get());
        System.out.println("future2结果: " + future2.join());

        System.out.println("主线程结束");
        customExecutor.shutdown(); // 关闭线程池
    }
}
